import { queryCardRelations, setIsOpenSalary } from '@/api/salary-card'
import user from '@/composables/user'

/**
 * 查询微工卡信息
 *
 * @param companyId 公司ID
 * @returns 返回Promise对象，解析后为薪资卡信息
 */
export function querySalaryCard(companyId: number) {
    return new Promise(async (resolve, reject) => {
        const res = await queryCardRelations({
            openid: user.userInfo.value?.openId || 0,
            companyId,
        }).catch(() => {
            reject(new Error('查询微工卡信息失败'))
        })

        if (res.registerState === undefined ? (res.authorizeState === 'AUTHORIZED') : (res.registerState === 'REGISTERED' && res.authorizeState === 'AUTHORIZED')) {
            // 判断员工是否开通微工卡

            if (!user.userInfo.value.isOpenSalaryCard && user.userInfo.value?.userId) {
                user.userInfo.value.isOpenSalaryCard = res.subMchid
                await setIsOpenSalary({
                    isOpenSalaryCard: res.subMchid,
                })
            }
            resolve(res)
        }
        else {
            if (res.isOpenSalaryCard) {
                // 已开通微工卡
                reject(true)
            }
            else {
                // 没有开通微工卡  如果该公司未授权微工卡，使用蓝豚互动的companyId
                const res = await queryCardRelations({
                    openid: user.userInfo.value?.openId || 0,
                })

                if (res.registerState === undefined ? (res.authorizeState === 'AUTHORIZED') : (res.registerState === 'REGISTERED' && res.authorizeState === 'AUTHORIZED')) {
                    if (!user.userInfo.value?.isOpenSalaryCard && user.userInfo.value?.userId) {
                        user.userInfo.value.isOpenSalaryCard = res.subMchid
                        await setIsOpenSalary({
                            isOpenSalaryCard: res.subMchid,
                        })
                    }
                    res.isOpenSalaryCard = false
                    resolve(res)
                }
                else {
                    reject(new Error('该企业未授权微工卡'))
                }
            }
        }
    }) as Promise<any>
}
